/**
 * 
 */
package com.jm.web.form.support;

import java.io.IOException;

import javax.servlet.jsp.JspWriter;

import com.jm.utils.AttributeBuilder;
import com.jm.utils.StringBuilderEx;
import com.jm.utils.StringHelper;
import com.jm.web.BasePage;
import com.jm.web.tags.support.DataSourceTag;

/**
 * @author yanjie
 *
 * 2011/9/20 上午10:25:19
 */
public class FieldItem extends EditItem{
	public final static String TAG_ITEMNAME = "FIELD";
	
	public final static String TAG_VALUE 			= "VALUE";//值
	public final static String TAG_CAPTION 			= "CAPTION";//标题
	public final static String TAG_CAPTIONWIDTH 	= "CAPTIONWIDTH";//标题的宽度
	public final static String TAG_CAPTION_DISPLAY	= "CAPTIONDISPLAY";//标题是否显示
	public final static String TAG_CAPTIONCSS		= "CAPTIONCSS";//标题是css
	public final static String TAG_CAPTIONCSS1		= "CAPTIONCSS1";//标题css1
	public final static String TAG_COLSPAN 			= "COLSPAN";//占几列
	public final static String TAG_REQUIRED			= "REQUIRED";//是否必填
	public final static String TAG_REQUIREDMSG		= "REQUIREDMSG";
	public final static String TAG_HIDDEN			= "HIDDEN";//是否隐藏
	public final static String TAG_RULE 			= "rule";//值规则
	public final static String TAG_MSG 				= "msg";//值规则消息
	
	protected String strValue = "";
	protected String strCaption = "";//标题
	protected String strCaptionWidth = "80px";//标题宽度
	protected String strCaptionCss = "";//标题css
	protected String strCaptionCss1 = "";//标题css
	protected boolean bcaptionDisplay = true;
	protected int iColspan = 1;
	protected boolean bRequired = false ;
	protected String strRequiredMsg = "";
	protected boolean bhidden = false ;
	protected String strRule = "";
	
	
	

	protected String strMsg = "";
	

	/**
	 * @param tag
	 */
	public FieldItem() {}
	
	public void init(){
		if(!this.isFromTag()){
			if(!this.parentIsFiledItem()){
				RegisterRulesScript();
				RegisterMessagesScript();
			}
			String strEvent = this.GetExtValue("event","").replaceAll("[|]",",").replaceAll(";",",");
			if(!StringHelper.IsNullOrEmpty(strEvent)){
				String event = "" ;
				String actiontemp = "" ;
				String actionvaluetemp = "" ;
				String ay[] = strEvent.split(",");
				if(ay.length > 0)
					event = ay[0];
				if(ay.length > 1)
					actiontemp = ay[1];
				if(ay.length > 2)
					actionvaluetemp = ay[2];
				
				StringBuilderEx sb = new StringBuilderEx();
				sb.Append("var el = $('#%1$s');",this.getId());
				sb.Append("el.%1$s(function(){",event);
					sb.Append("$('#actiontemp').val('%1$s');",actiontemp);
					sb.Append("$('#actionvaluetemp').val('%1$s');",actionvaluetemp);
					sb.Append("var ret = $P.validator['%1$s'].element($(this),true);",this.getBaseTag().getPage().getDefaultFormID());
					sb.Append("$('#actiontemp').val('');");
					sb.Append("$('#actionvaluetemp').val('');");
					sb.Append("if(ret || ret == undefined){$P.reseterror();$(this).trigger('vsucc');eval($(this).gv('vsucc'));}else{");
					sb.Append("$(this).trigger('onfail');eval($(this).gv('vfail'));");
					sb.Append("$(this).focus1(); return false;}");
				sb.Append("});");
				this.getBaseTag().getPage().RegisterOnReadyScript(BasePage.SCRIPTRUN_ONREADY,sb.toString());
			}
		}
		super.init();
	}
	
	/**
	 * 注册验证的规则
	 */
	protected void RegisterRulesScript(){
		StringBuilderEx sb = new StringBuilderEx();
		sb.Append("\r\n %1$s:{",this.getId());
		boolean bFirst = true ;
		if(this.isRequired()){
			sb.Append(bFirst ? "" : ",\r\n	");
			sb.Append("required:true");
			bFirst = false ;
		}
		
		if(!StringHelper.IsNullOrEmpty(this.getRule())){
			sb.Append(bFirst ? "" : ",\r\n	");
			sb.Append(this.getRule());
			bFirst = false ;
		}
		sb.Append("}");
		
		if(!bFirst){
			this.getBaseTag().getPage().RegisterOnReadyScript(BasePage.SCRIPTRUN_ONREADY,StringHelper.Format("$P.form.vformid.push('%1$s');",this.getId()));
			this.getBaseTag().getPage().RegisterRulesScript(sb.toString());
		}
			
	}
	
	/**
	 * 注册提示的消息
	 */
	protected void RegisterMessagesScript(){
		StringBuilderEx sb = new StringBuilderEx();
		sb.Append("\r\n	%1$s:{",this.getId());
		boolean bFirst = true ;
		if(!StringHelper.IsNullOrEmpty(this.getRequiredMsg())){
			sb.Append(bFirst ? "" : ",\r\n	");
			sb.Append("required:\"%1$s\"",this.getRequiredMsg());
			bFirst = false ;
		}
		
		if(!StringHelper.IsNullOrEmpty(this.getMsg())){
			sb.Append(bFirst ? "" : ",\r\n	");
			sb.Append(this.getMsg());
			bFirst = false ;
		}
		
		sb.Append("}");
		
		if(!bFirst)
			this.getBaseTag().getPage().RegisterMessagesScript(sb.toString());
	}
	
	/* 
	 * 输出filed 栏位的标题
	 */
	@Override
	public void onOutItemBegin(JspWriter writer) {
		StringBuilderEx sb = new StringBuilderEx();
		if(this.isCaptionDisplay() && !this.parentIsFiledItem()){
			if(this.isRequired()){
				this.setCaptionCss(StringHelper.Format("%1$s %2$s",this.getCaptionCss(),"required"));
			}
			sb.Append("<table class=\"sp_filed %1$s\"  border=\"0\" cellpadding=\"0px\" cellspacing=\"0px\" width=\"100%%\">","1".equals(this.GetExtValue("border","0")) ? "sp_filed_border" : "");
			sb.Append("<colgroup><col width=\"%1$s\" /><col width=\"*\"></colgroup>",this.getCaptionWidth());
			sb.Append("<tr><th class=\"%5$s\" style=\"%6$s\"><font id=\"%3$s_caption\" name=\"%4$s_caption\" class=\"%1$s\">%2$s </font></th>",
					this.getCaptionCss(),
					this.getCaption(),
					this.getId(),
					this.getName(),
					this.getCaptionCss1(),
					this.GetExtValue("captionStyle", "")
					);
			sb.Append("<td style=\"%1$s\" id=\"%2$s_body\">",this.GetExtValue("bodyStyle", ""),
					this.getId());
		}
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(!this.isFiledItem())
			super.onOutItemBegin(writer);//輸出input
	}
	
	@Override
	public void onOutItemEnd(JspWriter writer) {
		if(!this.isFiledItem())
			super.onOutItemEnd(writer);
		
		StringBuilderEx sb = new StringBuilderEx();
		if(this.isCaptionDisplay() && !this.parentIsFiledItem()){
			sb.Append("</td></tr>");
			sb.Append("</table>");
		}
		try {
			writer.write(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * @return
	 * 是否是filed控件 filed控件 里面的html代码会直接输出,不会重新解析,
	 */
	public boolean isFiledItem(){
		return TAG_ITEMNAME.equalsIgnoreCase(this.getNodeName());
	}
	
	public boolean parentIsFiledItem(){
		boolean bFiledItem = false;
		FormItem item = this.getParentItem();
		while(item != null){
			if(item instanceof FieldItem){
				bFiledItem = ((FieldItem)item).isFiledItem();
				if(bFiledItem)
					break;
			}
			item = item.getParentItem();
		}
		return bFiledItem;
	}
	
	@Override
	public void OnSetProperty(String strName, String strValue) {
		if (strName.compareToIgnoreCase(TAG_VALUE) == 0)
		{
			this.strValue = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_HIDDEN) == 0)
		{
			this.bhidden = StringHelper.GetValue(strValue, this.bhidden);
			if(this.isHidden()){
				OnSetProperty(FormItem.TAG_STYLE, "display:none;");
			}
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_CAPTION) == 0)
		{
			this.strCaption = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_CAPTIONWIDTH) == 0)
		{
			this.strCaptionWidth = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_CAPTIONCSS) == 0)
		{
			this.strCaptionCss = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_CAPTIONCSS1) == 0)
		{
			this.strCaptionCss1 = strValue;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_CAPTION_DISPLAY) == 0)
		{
			if("none".equals(strValue))
				this.bcaptionDisplay = false ;
			
			this.bcaptionDisplay = StringHelper.GetValue(strValue, this.bcaptionDisplay);
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_COLSPAN) == 0)
		{
			this.iColspan = StringHelper.GetValue(strValue, 1);
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_REQUIRED) == 0)
		{
			this.bRequired = StringHelper.GetValue(strValue, bRequired);
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_REQUIREDMSG) == 0)
		{
			this.strRequiredMsg = strValue ;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_RULE) == 0)
		{
			this.strRule = strValue ;
			return;
		}
		
		if (strName.compareToIgnoreCase(TAG_MSG) == 0)
		{
			this.strMsg = strValue;
			return;
		}
		
		super.OnSetProperty(strName, strValue);
	}
	
	/**
	 * 綁定數據
	 */
	protected void FillFiledItemValue(){
		if(this.getBaseTag() instanceof DataSourceTag){
			DataSourceTag dsTag = (DataSourceTag)this.getBaseTag();
			dsTag.FillFiledItemValue(this);
		}
	}
	
	@Override
	public void FillAttributeBuilder(AttributeBuilder attributesBuilder) {
		super.FillAttributeBuilder(attributesBuilder);
		attributesBuilder.Set(TAG_CAPTION.toLowerCase(),this.getCaption());
		
		//bind 参数用来控制此控件是否由平台来绑定数据
		if(this.GetExtValue("bind", true) && !TAG_ITEMNAME.equalsIgnoreCase(this.getNodeName()))
		{
			FillFiledItemValue();
		}
		
		if(!StringHelper.IsNullOrEmpty(this.getValue()) && !TAG_ITEMNAME.equalsIgnoreCase(this.getNodeName()))
		{
			attributesBuilder.Set(TAG_VALUE.toLowerCase(), this.getValue());
		}
		
		if(this.isFromTag()){
			if(this.isHidden())
				attributesBuilder.Set(TAG_HIDDEN.toLowerCase(), String.valueOf(this.isHidden()));
			
			if(!StringHelper.IsNullOrEmpty(this.getCaption()))
				attributesBuilder.Set(TAG_CAPTION.toLowerCase(), this.getCaption());
			
			if(!StringHelper.IsNullOrEmpty(this.getCaptionWidth()))
				attributesBuilder.Set(TAG_CAPTIONWIDTH.toLowerCase(), this.getCaptionWidth());
			
			if(!StringHelper.IsNullOrEmpty(this.getCaptionCss()))
				attributesBuilder.Set(TAG_CAPTIONCSS.toLowerCase(), this.getCaptionCss());
			
			if(!StringHelper.IsNullOrEmpty(this.getCaptionCss1()))
				attributesBuilder.Set(TAG_CAPTIONCSS1.toLowerCase(), this.getCaptionCss1());
			
			if(!this.isCaptionDisplay())
				attributesBuilder.Set(TAG_CAPTION_DISPLAY.toLowerCase(), String.valueOf(this.isCaptionDisplay()));
			
			if(this.getColspan() > 1)
				attributesBuilder.Set(TAG_COLSPAN.toLowerCase(), String.valueOf(this.getColspan()));
			
			if(this.isRequired())
				attributesBuilder.Set(TAG_REQUIRED.toLowerCase(), String.valueOf(this.isRequired()));
			
			if(!StringHelper.IsNullOrEmpty(this.getRequiredMsg()))
				attributesBuilder.Set(TAG_REQUIREDMSG.toLowerCase(), this.getRequiredMsg());
			
			if(!StringHelper.IsNullOrEmpty(this.getRule()))
				attributesBuilder.Set(TAG_RULE.toLowerCase(), this.getRule());
			
			if(!StringHelper.IsNullOrEmpty(this.getMsg()))
				attributesBuilder.Set(TAG_MSG.toLowerCase(), this.getMsg());
		}
	}
	
	
	public String getValue() {
		return strValue;
	}

	public void setValue(String strValue) {
		this.strValue = strValue;
	}
	
	public String getCaption() {
		return this.strCaption;
	}

	public void setCaption(String strCaption) {
		this.strCaption = strCaption;
	}

	public String getCaptionWidth() {
		return strCaptionWidth;
	}

	public void setCaptionWidth(String strCaptionWidth) {
		this.strCaptionWidth = strCaptionWidth;
	}
	
	public boolean isCaptionDisplay() {
		return bcaptionDisplay;
	}
	
	public void setCaptionDisplay(boolean bCaptionDisplay) {
		this.bcaptionDisplay = bCaptionDisplay;
	}
	
	public int getColspan() {
		return iColspan;
	}

	public void setColspan(int iColspan) {
		this.iColspan = iColspan;
	}
	
	public boolean isRequired() {
		return bRequired;
	}

	public void setRequired(boolean bRquired) {
		this.bRequired = bRquired;
	}
	
	public String getRequiredMsg() {
		return strRequiredMsg;
	}

	public void setRequiredMsg(String strRequiredMsg) {
		this.strRequiredMsg = strRequiredMsg;
	}
	
	public void setHidden(boolean bhidden) {
		this.bhidden = bhidden;
	}
	
	public boolean isHidden() {
		return bhidden;
	}
	
	public String getRule() {
		return strRule;
	}

	public void setRule(String strRule) {
		this.strRule = strRule;
	}

	public String getMsg() {
		return strMsg;
	}

	public void setMsg(String strMsg) {
		this.strMsg = strMsg;
	}

	public String getCaptionCss() {
		return strCaptionCss;
	}

	public void setCaptionCss(String strCaptionCss) {
		this.strCaptionCss = strCaptionCss;
	}
	
	public String getCaptionCss1() {
		return strCaptionCss1;
	}

	public void setCaptionCss1(String strCaptionCss1) {
		this.strCaptionCss1 = strCaptionCss1;
	}
}
